﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Retail.Models.DBModels;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Serializer;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;
using static Yunzuan.Foundation.Web_api.MyHttpRequest;

namespace Yunzuan.Common.Interface
{
    /// <summary>
    /// 零售或二级公共相关
    /// </summary>
    public class CRetails
    {
        #region 产品公用模块
        /// <summary>
        /// 产品公用模块（包含成品，统包，彩宝等）
        /// </summary>
        /// <param name="getInlaysParam">当前产品对应参数</param>
        /// <param name="requestUrl">产品请求URL</param>
        /// <returns></returns>
        public static string AllProduct(string tttagKey, string getProductParam, string requestUrl, string method = "post", bool isOriginalJson = false)
        {
            var logParam = string.Format("getProductParam:{0}, requestUrl{1},  method{2} ,  isOriginalJson{3} ", getProductParam, requestUrl, method, isOriginalJson);
            method = method.ToLower();
            try
            {
                MyHttpRequest.RequestLib lib = new MyHttpRequest.RequestLib();
                //获取在线成品（含签名）  
                switch (method)
                {
                    case "delete":
                        lib = MyHttpRequest.RequestLib.DELETE;
                        break;
                    case "put":
                        lib = MyHttpRequest.RequestLib.PUT;
                        break;
                    case "get":
                        lib = MyHttpRequest.RequestLib.GET;
                        break;
                    default:  //POST
                        lib = MyHttpRequest.RequestLib.POST;
                        break;
                }
                var responseJson = MyHttpClient.GetRsultFromDataCenterNew(tttagKey, requestUrl, getProductParam, 2, null, lib);
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：产品公用模块（包含成品，统包，彩宝等）" + ex.StackTrace);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        public static string GetIdsStrParamByIds(int[] xxIds, string key = "")
        {
            StringBuilder sbIds = new StringBuilder();
            for (int i = 0; i < xxIds.Length; i++)
            {
                sbIds.Append("\"" + xxIds[i] + "\",");
            }
            if (key == "")
                return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
            else
                return string.Format(" {{\"useDict\": true,\"ID\":[{0}],\"TagKey\":\"{1}\"}}", sbIds.ToString().TrimEnd(','), key);
        }

        private static void GetKey(string key, ref string tagkey, ref string secondSN)
        {
            if (key.Contains("__"))
            {
                string[] keys = key.Replace("__","$").Split('$');
                tagkey = keys[0];
                secondSN = keys[1];
            }
            else
            {
                tagkey = key;
                secondSN = "";
            }
        }
        #endregion


        /// <summary>
        /// 采购订单（处理（1下单成功，待采购）的订单到 (2采购成功，待入库)） --含事务    （改变订单状态 从1到2）
        /// </summary>
        /// <param name="purchaseOrdersParam"></param>
        /// <returns></returns>
        public static string PurchaseOrder(string purchaseOrderParam)
        {
            var logParam = purchaseOrderParam;
            HashParam param = Json.Deserialize<HashParam>(purchaseOrderParam);
            string tttagKey = CommonUrl.getURL(param, purchaseOrderParam);
            string secondSN = "";
            string SupplierKey = "";
            {
                CRetails.GetKey(tttagKey, ref SupplierKey, ref secondSN);
            }
            try
            {
                if (string.IsNullOrEmpty(param.GetString("OrderID")))
                {
                    return CommonLog.MsgErrorInfo("采购失败，没选择任何订单");
                }
                OrderInfo order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", param.GetInt("OrderID"));
                if (order != null && order.GoodsTypeID == GoodsType.Diamond)
                {
                    Inventory _inventory = Json.Deserialize<Inventory>(order.InventoryAttribute);
                    _inventory.Shape = param.GetInt("Shape").Value;
                    _inventory.Weight = param.GetDecimal("Weight").Value; 
                    _inventory.Color = param.GetString("Color");
                    _inventory.Clarity = param.GetString("Clarity");
                    _inventory.Cut = param.GetString("Cut");
                    _inventory.Polish = param.GetString("Polish");
                    _inventory.Symmetry = param.GetString("Symmetry");
                    _inventory.Fluorescence = param.GetString("Fluorescence");
                    _inventory.CertType = param.GetString("CertType");
                    _inventory.CertNo = param.GetString("CertNo");
                    _inventory.Supplier = param.GetString("SupplierCode");
                    _inventory.OriginSN = param.GetString("OriginSN");
                    _inventory.OriginDiscountReturn = param.GetDecimal("DiscountReturn").Value;
                    _inventory.OriginUSDPerGrain = param.GetDecimal("PriceUSD").Value;
                    //修改属性后保存到订单的属性中
                    order.InventoryAttribute = JsonConvert.SerializeObject(_inventory);
                    //采购汇率
                    order.PurchaseExchangerate = param.GetDecimal("PurchaseExchangerate").Value;
                    order.Remarks = param.GetString("PurchaseRemarks");
                    order.PurchaseReturn = param.GetDecimal("DiscountReturn").Value;
                    order.ModifyTime = DateTime.Now;
                }
                else if (order != null && order.GoodsTypeID == GoodsType.Ring)//成品
                {
                    Ring ring = Json.Deserialize<Ring>(order.InventoryAttribute);
                    ring.OriginSN = param.GetString("OriginSN");
                    ring.Series = param.GetString("Series");
                    ring.Style = param.GetInt("Style").Value;
                    ring.Material = param.GetString("Material");
                    ring.Measurement = param.GetString("Measurement");
                    ring.Country = param.GetString("Country");
                    ring.State = param.GetString("State");
                    ring.Type = param.GetInt("Type").Value;
                    ring.MainClarity = param.GetString("MainClarity");
                    ring.MainColor = param.GetString("MainColor");
                    ring.CertType = param.GetString("CertType");
                    ring.MainCertType = param.GetString("MainCertType");
                    ring.MainCertNo = param.GetString("MainCertNo");
                    ring.IsStock = param.GetInt("IsStock").Value;
                    ring.Supplier = param.GetString("Supplier");
                    ring.Price = param.GetDecimal("PurchaseRMB").Value;
                    order.InventoryAttribute = JsonConvert.SerializeObject(ring);
                    //采购汇率
                    order.PurchaseExchangerate = param.GetDecimal("PurchaseExchangerate").Value;
                    order.Remarks = param.GetString("Remark");
                    order.ModifyTime = DateTime.Now;

                }
                else if (order != null && order.GoodsTypeID == GoodsType.InlaySettings)//空托
                {
                    InlaySettings inlaySettings = Json.Deserialize<InlaySettings>(order.InventoryAttribute);
                    #region 空托
                    inlaySettings.StyleNo = param.GetString("StyleNo");
                    inlaySettings.OriginSN = param.GetString("OriginSN");
                    inlaySettings.Technics = param.GetInt("Technics").Value;
                    inlaySettings.Type = param.GetInt("Type").Value;
                    inlaySettings.Style = param.GetInt("Style").Value;
                    inlaySettings.Series = param.GetString("Series");
                    inlaySettings.Material = param.GetInt("Material").Value;
                    inlaySettings.MainShape = param.GetInt("MainShape").Value;
                    inlaySettings.MainWeight = param.GetDecimal("MainWeight").Value;
                    inlaySettings.SideWeight = param.GetDecimal("SideWeight").Value;
                    inlaySettings.SideNum = param.GetInt("SideNum").Value;
                    inlaySettings.Measurement = param.GetString("Measurement");
                    inlaySettings.GoldPrice = param.GetDecimal("GoldPrice").Value;
                    inlaySettings.Wastage = param.GetDecimal("Wastage").Value;
                    inlaySettings.SideLaborFee = param.GetDecimal("SideLaborFee").Value;
                    inlaySettings.SidePrice = param.GetDecimal("SidePrice").Value;
                    inlaySettings.LaborFee = param.GetDecimal("LaborFee").Value;
                    inlaySettings.Insurance = param.GetDecimal("Insurance").Value;
                    inlaySettings.Manufactor = param.GetString("Manufactor");
                    inlaySettings.Country = param.GetString("Country");
                    inlaySettings.State = param.GetString("State");
                    order.PurchaseRMB = param.GetDecimal("PurchaseRMB").Value;
                    #endregion
                    order.InventoryAttribute = JsonConvert.SerializeObject(inlaySettings);
                    //采购汇率
                    //order.PurchaseExchangerate = param.GetDecimal("PurchaseExchangerate").Value;
                    order.Remarks = param.GetString("PurchaseRemarks");
                    order.ModifyTime = DateTime.Now;
                }
                else
                {
                    return CommonLog.MsgErrorInfo("采购失败，订单标识不存在");//OrderID不存在的情况(单个操作好判断)
                }

                //计算价格 2017-03-01
                #region
                RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                if (order.GoodsTypeID == 1)
                {
                    Inventory _inventory = Json.Deserialize<Inventory>(order.InventoryAttribute);
                    if (param.GetString("IsFancy") == "0")
                    {
                        order.Rapnet = rap.GetPrice(_inventory);
                        //白钻以退点为准
                        order.PurchaseUSD = param.GetDecimal("Weight") * order.Rapnet * ((100 + order.PurchaseReturn) / 100);
                        order.PurchaseRMB = order.PurchaseUSD * order.PurchaseExchangerate;
                    }
                    else
                    {
                        order.Rapnet = 0;
                        order.PurchaseReturn = 0;
                        //彩钻以总价为准
                    }
                }
                #endregion
                //订单状态 （2采购成功，待入库）
                if (order.OrderStatus == 1)
                {
                    if (order.Supplier == SupplierKey && order.BuyExchangerate!=null)
                    {
                        order.OrderStatus = 3;//待出货
                    }
                    else
                    {
                        order.OrderStatus = 2;//待到货 从 1待采购 到 2待到货 ;其余为修改采购信息 11-3
                    }
                }
                using (ITransaction trans_purchaseOrders = YZ.GetTransaction(tttagKey))
                {
                    int pruchaseOrdersResult = trans_purchaseOrders.Edit(order);
                    //单条成功后，就执行采购订单事务
                    if (pruchaseOrdersResult > 0)
                    {
                        try
                        {
                            trans_purchaseOrders.CommitTransaction(); //执行事务
                            return CommonLog.MsgSuccessInfo("采购成功");
                        }
                        catch (Exception)
                        {
                            trans_purchaseOrders.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("采购失败");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("采购失败，订单标识不存在");//OrderID不存在的情况(单个操作好判断)
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("采购失败，程序错误");
            }
        }
        public static void GetMethodInfoAndWriteLogs(Exception ex)
        {
            CommonLog.GetMethodInfoAndWriteLogs(typeof(AllPublic), ex);
        }
        #region 裸钻现货库存管理
        /// <summary>
        /// 新增或者回库
        /// </summary>
        /// <param name="hsParam"></param>
        /// <param name="tttagKey"></param>
        /// <returns></returns>
        public static string AddDia(HashParam hsParam, string tttagKey, string SupplierKey="")
        {
            try
            {
                #region
                long? _orderID = hsParam.GetInt("OrderID");
                OrderInfo _order = null;
                if (hsParam.GetString("OrderID") != "")
                {
                    _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", _orderID);
                    if ((SupplierKey!=""&& _order.Supplier == SupplierKey)||(_order.Supplier == tttagKey))
                    {
                        #region  现货删除订单
                        string[] _inventoryIDs = _order.InventoryID == null ? "0".Split(',') : _order.InventoryID.ToString().TrimEnd(',').Split(',');
                        int[] InventoryIDs = new int[_inventoryIDs.Length];
                        for (int i = 0; i < _inventoryIDs.Length; i++)
                        {
                            InventoryIDs[i] = Convert.ToInt32(_inventoryIDs[i]);//不能为空
                        }
                        TransmissionOrderResult delOrderResult = OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单 
                        if (delOrderResult.Result)
                        {
                            #region  更新订单状态
                            if (_order != null)
                            {
                                _order.Online = 1;//1已回库 空 待回库
                                using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                                {
                                    int editOrderResult = trans_editOrder.Edit(_order);
                                    if (editOrderResult > 0)
                                    {
                                        //继续
                                        try
                                        {
                                            hsParam.Add("ID", hsParam["InventoryID"]);
                                            hsParam.Remove("InventoryID");//移除InventoryID属性
                                            hsParam.Remove("Supplier");// 
                                            hsParam.Remove("OrderID");// 
                                            UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", hsParam.GetString("PurchaseAgent"));
                                            if (userinfo != null)
                                                hsParam["PurchaseAgent"] = userinfo.UserName;
                                            string PurchaseTime1 = hsParam.GetString("PurchaseTime").Trim();
                                            if (PurchaseTime1 == "")
                                                hsParam.Remove("PurchaseTime");
                                            else
                                            {
                                                hsParam["PurchaseTime"] = PurchaseTime1;
                                                if (Convert.ToDateTime(PurchaseTime1).Year < 1971)
                                                {
                                                    hsParam.Remove("PurchaseTime");
                                                }
                                            }
                                            string ArrivalTime1 = hsParam.GetString("ArrivalTime").Trim();
                                            if (ArrivalTime1 == "")
                                                hsParam.Remove("ArrivalTime");
                                            else
                                            {
                                                hsParam["ArrivalTime"] = ArrivalTime1;
                                                if (Convert.ToDateTime(ArrivalTime1).Year < 1971)
                                                {
                                                    hsParam.Remove("ArrivalTime");
                                                }
                                            }
                                            #region
                                            object[] str = { hsParam };
                                            Dictionary<string, object> tempParam = new Dictionary<string, object>();//组装 
                                            tempParam.Add("rows", str);
                                            string lastParam = JsonConvert.SerializeObject(tempParam);//{ "rows":[{},{}]}
                                            #endregion
                                            TransmissionOrderResult tor = new TransmissionOrderResult();
                                            int totalSeconds;
                                            string signStr;
                                            var guid = Guid.NewGuid().ToString();
                                            var objParams = JsonConvert.DeserializeObject<JObject>(lastParam);
                                            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                                            MyHttpRequest.SignByParams(guid, lastStr.ToString(), tttagKey, out totalSeconds, out signStr);
                                            //获取数据仓库库存（远程） 多个ID获取多条库存
                                            //{ "rows":[{},{}]}
                                            var result =
                                                 MyHttpRequest.PostJSONByRequestParam(
                                                    new RequestInfo() { RequestJson = lastParam, RequestUrl = GlobalConfig.TransmissionUpStockURL }  //编辑库存
                                                     , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                                            );
                                            CommonLog.SendMQMsg(tttagKey, "新增裸钻：数据中心返回结果1" + result);
                                            if (result.Contains("count_update") && result.Contains("count_insert"))
                                            {
                                                trans_editOrder.CommitTransaction(); //提交事务
                                                return CommonLog.MsgSuccessInfo("回库成功");
                                            }
                                            return CommonLog.MsgErrorInfo("回库失败");
                                        }
                                        catch (Exception ex)
                                        {
                                            GetMethodInfoAndWriteLogs(ex);
                                            CommonLog.SendMQMsg(tttagKey, "异常信息：新增裸钻1" + ex.StackTrace + "参数:" + JsonConvert.SerializeObject(hsParam));
                                            trans_editOrder.RollBackTransaction();//回滚事务
                                            return CommonLog.MsgErrorInfo("回库失败,请重试");
                                        }
                                    }
                                    else
                                    {
                                        trans_editOrder.RollBackTransaction();//回滚事务
                                        return CommonLog.MsgErrorInfo("更新订单失败");
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion
                    }
                } 
                #endregion
                hsParam.Remove("OrderID");//移除OrderID属性 12-16
                hsParam.Remove("InventoryID");//移除InventoryID属性
                //回库操作需要删除SupplierCode，否则会报错  2017-11-15
                hsParam.Remove("SupplierCode");//回库需删除SupplierCode属性
                //_beforeParam.Remove("BuyUSDPrice");
                //_beforeParam.Remove("BuyRMBPrice"); 
                hsParam.Remove("SalesExchangerate");
                hsParam.Remove("PurchaseUSD");
                hsParam.Remove("PurchaseRMB");
                hsParam.Remove("BuyPurchaseSupplier"); 
                hsParam.Remove("BuyPurchaseTime"); 
                hsParam.Remove("BuyDis");
                string ShipTime = hsParam.GetString("ShipTime").Trim();
                if (ShipTime == "")
                    hsParam.Remove("ShipTime");
                else
                {
                    hsParam["ShipTime"] = ShipTime;
                    if (Convert.ToDateTime(ShipTime).Year < 1971)
                    {
                        hsParam.Remove("ShipTime");
                    }
                }
                UserInfo user = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", hsParam.GetString("PurchaseAgent"));
                if (user != null)
                    hsParam["PurchaseAgent"] = user.UserName;
                string PurchaseTime = hsParam.GetString("PurchaseTime").Trim();
                if (PurchaseTime == "")
                    hsParam.Remove("PurchaseTime");
                else
                {
                    hsParam["PurchaseTime"] = PurchaseTime;
                    if (Convert.ToDateTime(PurchaseTime).Year < 1971)
                    {
                        hsParam.Remove("PurchaseTime");
                    }
                }
                string ArrivalTime = hsParam.GetString("ArrivalTime").Trim();
                if (ArrivalTime == "")
                    hsParam.Remove("ArrivalTime");
                else
                {
                    hsParam["ArrivalTime"] = ArrivalTime;
                    if (Convert.ToDateTime(ArrivalTime).Year < 1971)
                    {
                        hsParam.Remove("ArrivalTime");
                    }
                }
                //组装参数
                #region
                Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(hsParam));
                object[] str1 = { param };
                Dictionary<string, object> tempParam1 = new Dictionary<string, object>();//组装 
                tempParam1.Add("rows", str1);
                string lastParam1 = JsonConvert.SerializeObject(tempParam1);//把{} 组装成 { "rows":[{},{}]}
                #endregion
                TransmissionOrderResult tor1 = new TransmissionOrderResult();
                int totalSeconds1;
                string signStr1;
                var guid1 = Guid.NewGuid().ToString();
                var objParams1 = JsonConvert.DeserializeObject<JObject>(lastParam1);
                var lastStr1 = MyHttpRequest.NestedDictSort2Str(objParams1);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid1, lastStr1.ToString(), tttagKey, out totalSeconds1, out signStr1);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result1 =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = lastParam1, RequestUrl = GlobalConfig.TransmissionUpStockURL }     //添加库存  lastParam 为 { "rows":[{},{}]}
                         , 3, guid1, signStr1, totalSeconds1, null, MyHttpRequest.RequestLib.POST
                );
                CommonLog.SendMQMsg(tttagKey, "新增裸钻：数据中心返回结果2" + result1);
                if (result1.Contains("count_update") && result1.Contains("count_insert"))
                {
                    //更新回库状态Online为1已上线
                    #region
                    if (_order != null)
                    {
                        #region
                        if (_order.Supplier != tttagKey)
                        {
                            //删除数据中心订单
                            //{\"count\": 1, \"ids_insert\": [], \"ids\": [12076947], \"ids_update\": [12076947], \"result\": true, \"count_update\": 1, \"count_insert\": 0}
                            string pattern = @"\d{6,12}";
                            bool b = false;
                            foreach (Match match in Regex.Matches(result1, pattern))
                            {
                                b = true;
                                int[] InventoryIDs = new int[1];
                                InventoryIDs[0] = Convert.ToInt32(match.Value);
                                TransmissionOrderResult delOrderResult = OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单 
                                break;
                            }
                            if (!b)
                            {
                                //记录result 的值，看看为什么无法匹配上述正则 
                                //GetMethodInfoAndWriteLogs(null, string.Format("删除对应的其它供应商回库的货失败，result:{0}", result1));
                            }
                        }
                        #endregion
                        _order.Online = 1;//1已回库 空 待回库
                        using (ITransaction trans_editOrder = YZ.GetTransaction(tttagKey))
                        {
                            int editOrderResult = trans_editOrder.Edit(_order);
                            if (editOrderResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("更新订单失败");
                            }
                            try
                            {
                                trans_editOrder.CommitTransaction(); //提交事务
                            }
                            catch (Exception ex)
                            {
                                GetMethodInfoAndWriteLogs(ex);
                                CommonLog.SendMQMsg(tttagKey, "异常信息：" + ex.StackTrace + "参数:" + JsonConvert.SerializeObject(hsParam));
                                trans_editOrder.RollBackTransaction();//回滚事务
                                return CommonLog.MsgErrorInfo("失败,请重试");
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    result1 = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return result1;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：新增裸钻2" + ex.StackTrace + "参数:" + JsonConvert.SerializeObject(hsParam));
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="hsParam"></param>
        /// <param name="tttagKey"></param>
        /// <returns></returns>
        public static string DelDia(HashParam hsParam, string tttagKey)
        {
            try
            {
                var strParam = JsonConvert.SerializeObject(hsParam);
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var ids = hsParam.GetString("id");//id可单个和批量 11-22
                var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = strParam, RequestUrl = GlobalConfig.TransmissionUpStockURL + "?id=" + ids }  //删除Delete
                         , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.DELETE
                );
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return result;//成功true
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 更新裸钻
        /// </summary>
        /// <param name="udateInventoryParam"></param>
        /// <returns></returns>
        public static string ModifyDia(HashParam hsParam, string tttagKey)
        {
            try
            {
                //把{} 组装成 { "rows":[{},{}]}   11-23
                #region

                #region  防止修改保存后买入时间为空
                //获取对象  
                hsParam["PurchaseTime"] = hsParam["PurchaseTime"].ToString().Trim();
                if (string.IsNullOrEmpty(hsParam["PurchaseTime"].ToString()))
                {
                    hsParam.Remove("PurchaseTime");
                }
                hsParam["ShipTime"] = hsParam["ShipTime"].ToString().Trim();
                if (string.IsNullOrEmpty(hsParam["ShipTime"].ToString()))
                {
                    hsParam.Remove("ShipTime");
                }
                hsParam["ArrivalTime"] = hsParam["ArrivalTime"].ToString().Trim();
                if (string.IsNullOrEmpty(hsParam["ArrivalTime"].ToString()))
                {
                    hsParam.Remove("ArrivalTime");
                }
                #endregion
                object[] str = { hsParam };
                Dictionary<string, object> tempParam = new Dictionary<string, object>();//组装 
                tempParam.Add("rows", str);
                string lastParam = JsonConvert.SerializeObject(tempParam);//{ "rows":[{},{}]}
                #endregion
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(lastParam);
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                //{ "rows":[{},{}]}
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = lastParam, RequestUrl = GlobalConfig.TransmissionUpStockURL }  //编辑库存
                         , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                );
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("远程服务错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string BatchUpdataDia(string strParam, string requestUrl, RequestLib reqLib = RequestLib.PUT, string msg = "")
        {
            strParam = strParam.Replace("SourceDiscountReturn", "OriginDiscountReturn").Replace("SourceDolarPerGrain", "OriginUSDPerGrain").Replace("SourceDolarPerCarat", "OriginUSDPerCarat");
            var logParam = strParam;
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam, "批量修改零售二级裸钻");

            strParam = JsonConvert.SerializeObject(hsParam);
            try
            {
                TransmissionOrderResult tor = new TransmissionOrderResult();
                int totalSeconds;
                string signStr;
                var guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                //获取数据仓库库存（远程） 多个ID获取多条库存
                var result =
                     MyHttpRequest.PostJSONByRequestParam(
                        new RequestInfo() { RequestJson = strParam, RequestUrl = requestUrl }
                         , 3, guid, signStr, totalSeconds, null, reqLib);
                if (result.Contains(".py"))
                {
                    result = CommonLog.MsgErrorInfo("数据远程服务错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("编辑，服务器内部错误");
            }
        }
        /// <summary>
        /// 付款
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string UpdateReciptStatus(HashParam hsParam, string tttagKey)
        {
            try
            {
                var param = "";
                using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                {
                    #region 增加付款账户 流水记录
                    decimal? totalRMB = 0, totalUSD = 0;
                    BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", hsParam.GetInt("BankID"));
                    if (_bank != null)
                    {
                        //Currency=1   是RMB  2是美金 
                        if (hsParam.GetInt("Currency") == 1 && hsParam.GetInt("Currency") == _bank.Currency)
                        {
                            if (_bank.BankBalance >= Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney"))) && _bank.BankBalance > 0)
                            {
                                _bank.BankBalance = _bank.BankBalance + (-Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney"))));//加减数 
                                totalRMB += Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney")));
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("【全部付】￥账户余额不足");
                            }
                        }
                        else if (hsParam.GetInt("Currency") == 2 && hsParam.GetInt("Currency") == _bank.Currency)
                        {
                            if (_bank.BankBalance >= Convert.ToDecimal(hsParam.GetString("TotalMoney")) && _bank.BankBalance > 0)
                            {
                                _bank.BankBalance = _bank.BankBalance + (-Convert.ToDecimal(hsParam.GetString("TotalMoney")));//加减数 
                                totalUSD += Convert.ToDecimal(hsParam.GetString("TotalMoney"));
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("【全部付】$账户余额不足");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("请选择对应币种的账户");
                        }
                        //更新账户余额
                        #region
                        int editBalanceResult = trans_payOrders.Edit(_bank);//更新客户余额事务 要用Edit 
                        if (editBalanceResult > 0)
                        {
                        }
                        else
                        {
                            //跳出
                            return CommonLog.MsgErrorInfo("账户不存在");
                        }
                        #endregion
                        //生成流水
                        #region
                        FlowInfo _flow = new FlowInfo();
                        _flow.CreateTime = DateTime.Now;
                        _flow.UpdateTime = DateTime.Now;
                        if (_bank.Currency == 1)
                        {
                            _flow.Amount = totalRMB;
                        }
                        else if (_bank.Currency == 2)
                        {
                            _flow.Amount = totalUSD;
                        }
                        _flow.Balance = _bank.BankBalance;
                        _flow.Currency = _bank.Currency;
                        _flow.Account = _bank.BankID;
                        _flow.Type = 2;
                        _flow.Abstract = 0;//0订单付款
                        _flow.Purpose = 1;//1裸钻 
                        _flow.ApplyID = hsParam.GetInt("ApplyID");
                        _flow.ReviewID = hsParam.GetInt("ApplyID");
                        _flow.ArrivalTime = hsParam.GetDataTime("ArrivalTime");
                        _flow.Status = 1;
                        _flow.Remarks = "现货付款" + (_flow.Currency == 1 ? "RMB" : "$") + "[" + _flow.Amount + "]";
                        int addFlowResult = trans_payOrders.Add(_flow);
                        if (addFlowResult > 0)
                        {
                            //继续
                            hsParam.Remove("BankID");
                            hsParam.Remove("ArrivalTime");
                            hsParam.Remove("TotalMoney");
                            hsParam.Remove("ApplyID");
                            hsParam.Remove("Currency");
                            param = JsonConvert.SerializeObject(hsParam);


                            #region 更新数据中心付款状态
                            TransmissionOrderResult tor = new TransmissionOrderResult();
                            int totalSeconds;
                            string signStr;
                            var guid = Guid.NewGuid().ToString();
                            var objParams = JsonConvert.DeserializeObject<JObject>(param);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                            MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                            //获取数据仓库库存（远程） 多个ID获取多条库存
                            var result =
                                 MyHttpRequest.PostJSONByRequestParam(
                                    new RequestInfo() { RequestJson = param, RequestUrl = GlobalConfig.TransmissionBatchUpStockURL }
                                     , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                            );
                            if (result.Contains(".py"))
                            {
                                trans_payOrders.RollBackTransaction();// 
                                result = CommonLog.MsgErrorInfo("数据远程服务错误");
                            }
                            if (result.Split(':')[1].Replace("}", "").Trim() == "true")
                            {
                                result = CommonLog.MsgSuccessInfo("修改成功");
                                trans_payOrders.CommitTransaction();//更新成功
                            }
                            else
                            {
                                trans_payOrders.RollBackTransaction();
                                result = CommonLog.MsgErrorInfo(result);
                            }
                            return result;
                            #endregion
                        }
                        else
                        {
                            //跳出
                            trans_payOrders.RollBackTransaction();//更新成功
                            return CommonLog.MsgErrorInfo("生成流水失败");
                        }
                        #endregion
                    }
                    else
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("账户不存在,检查账户标识");
                    }
                    #endregion
                }

            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #endregion
        #region 订单
        /// <summary>
        /// 提交订单  删除订单 获取订单 （公共方法）
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="action"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static TransmissionOrderResult OprationOrders(int[] ids, string action, string key, int count = 3)
        {
            try
            {
                if (count > 0)
                {
                    TransmissionOrderResult tor = new TransmissionOrderResult();
                    count--;
                    StringBuilder sbIds = new StringBuilder();
                    for (int i = 0; i < ids.Length; i++)
                    {
                        sbIds.Append(ids[i] + ",");
                    }
                    Dictionary<string, object> postData = new Dictionary<string, object>();
                    var strIds = sbIds.ToString().TrimEnd(',');
                    postData["id"] = strIds;
                    int totalSeconds;
                    string signStr;
                    var guid = Guid.NewGuid().ToString();
                    var lastStr = MyHttpRequest.ShotDic1(postData);
                    MyHttpRequest.SignByParams(guid, lastStr.ToString(), key, out totalSeconds, out signStr);
                    RequestInfo rif = new RequestInfo() { RequestJson = JsonConvert.SerializeObject(postData), RequestUrl = GlobalConfig.OUrl + "?id=" + strIds };
                    string returnJson = "";
                    if (action.ToLower() == "add")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST);  //提交订单
                    else if (action.ToLower() == "get")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET);  //获取订单
                    else if (action.ToLower() == "del")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.DELETE);  //删除订单
                    if (returnJson.Contains(".py") && returnJson.Contains("Error:"))
                    {
                        tor.MessageInfo = "远程接口出错,出错信息：" + returnJson.Substring(returnJson.IndexOf("Error:") + 6, returnJson.Length - (returnJson.IndexOf("Error:") + 6));
                        return tor;
                    }
                    else
                    {
                        tor = JsonConvert.DeserializeObject<TransmissionOrderResult>(returnJson);  //返回成功订单ID
                        if (action.ToLower() == "get")
                        {
                            tor.MessageInfo = returnJson; //获取订单的详情
                        }
                        return tor;
                    }
                }
                else
                {
                    TransmissionOrderResult tor = new TransmissionOrderResult() { Result = false, MessageInfo = "网络连接失败" };
                    return tor;
                }
            }
            catch (Exception ee)
            {
                GetMethodInfoAndWriteLogs(ee);
                return OprationOrders(ids, action, key, count);
            }
        }
        #endregion
        #region 除裸钻外现货增删改
        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string AddProductData(string strParam, string tttagKey, int goodsType)
        {
            if (goodsType == GoodsType.Parcel)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, ""), "post");
            }
            else if (goodsType == GoodsType.Ring)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ""), "post");
            }
            else if (goodsType == GoodsType.Gem)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, ""), "post");
            }
            else if (goodsType == GoodsType.Emerald)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, ""), "post");
            }
            else if (goodsType == GoodsType.PrimeGolds)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, ""), "post");
            }
            if (goodsType == GoodsType.InlaySettings)
            {
                return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, ""), "post");
            }
            return "";

        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string DelProductData(string strParam)
        { 
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            if (hsParam.ContainsKey("GoodsType"))
            {
                int goodsType = hsParam.GetInt("GoodsType").Value;
                hsParam.Remove("GoodsType");
                strParam = JsonConvert.SerializeObject(hsParam);
                if (goodsType == GoodsType.Parcel)
                {
                    Parcels parcel = Json.Deserialize<Parcels>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionParcelOprateUrl, parcel.ID), "delete");
                }
                else if (goodsType == GoodsType.Ring)
                {
                    Ring ring = Json.Deserialize<Ring>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ring.ID), "delete");
                }
                else if (goodsType == GoodsType.Gem)
                {
                    Gem gem = Json.Deserialize<Gem>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionGemOprateUrl, gem.ID), "delete");
                }
                else if (goodsType == GoodsType.Emerald)
                {
                    Emerald emerald = Json.Deserialize<Emerald>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, emerald.ID), "delete");
                }
                else if (goodsType == GoodsType.PrimeGolds)
                {
                    PrimeGolds primeGolds = Json.Deserialize<PrimeGolds>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, primeGolds.ID), "delete");
                }
                else if (goodsType == GoodsType.InlaySettings)
                {
                    InlaySettings inlaySettings = Json.Deserialize<InlaySettings>(strParam);
                    return AllProduct(tttagKey, "{}", string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, inlaySettings.ID), "delete");
                }
            }
            else
            {
                return CommonLog.MsgErrorInfo("未指定商品类别");
            }
            return "";
        }
        /// <summary>
        /// 现货修改
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string ModifyProductData(string strParam)
        { 
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam); 
            if (hsParam.ContainsKey("GoodsType"))
            {
                int goodsType = hsParam.GetInt("GoodsType").Value;
                {
                    //删除不用的参数
                    hsParam.Remove("GoodsType");
                    hsParam.Remove("TagKey");
                    hsParam.Remove("ActiveIP");
                    hsParam.Remove("OperationUserId");
                    hsParam.Remove("HttpUrl");
                    hsParam.Remove("Browser");
                    hsParam.Remove("OpeartionSystem");
                    strParam = JsonConvert.SerializeObject(hsParam);
                }
                string filterUrl = "";
                if (goodsType == GoodsType.Parcel)
                {
                    Parcels parcel = Json.Deserialize<Parcels>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.Parcel);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { parcel.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<Parcels> list = JsonConvert.DeserializeObject<Products<Parcels>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (list.Rows[0].ReceiptStatus == parcel.ReceiptStatus)
                        { 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionParcelOprateUrl, parcel.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
                else if (goodsType == GoodsType.Ring)
                {
                    Ring ring = Json.Deserialize<Ring>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.Ring);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { ring.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<Ring> list = JsonConvert.DeserializeObject<Products<Ring>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (string.IsNullOrEmpty(ring.StyleNo))
                        {
                            return CommonLog.MsgErrorInfo("款号不能为空");
                        }
                        if (list.Rows[0].ReceiptStatus == ring.ReceiptStatus)
                        { 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionInlaysOprateUrl, ring.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
                else if (goodsType == GoodsType.Gem)
                {
                    Gem gem = Json.Deserialize<Gem>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.Gem);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { gem.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<Gem> list = JsonConvert.DeserializeObject<Products<Gem>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (list.Rows[0].ReceiptStatus == gem.ReceiptStatus)
                        { 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionGemOprateUrl, gem.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
                else if (goodsType == GoodsType.Emerald)
                {
                    Emerald emerald = Json.Deserialize<Emerald>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.Emerald);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { emerald.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<Emerald> list = JsonConvert.DeserializeObject<Products<Emerald>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (list.Rows[0].ReceiptStatus == emerald.ReceiptStatus)
                        { 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionEmeraldOprateUrl, emerald.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
                else if (goodsType == GoodsType.PrimeGolds)
                {
                    PrimeGolds primeGolds = Json.Deserialize<PrimeGolds>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.PrimeGolds);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { primeGolds.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<PrimeGolds> list = JsonConvert.DeserializeObject<Products<PrimeGolds>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (list.Rows[0].ReceiptStatus == primeGolds.ReceiptStatus)
                        {
                            //`GoldPrice` decimal(12,3) NOT NULL DEFAULT '0.000' COMMENT '金价', # 不支持新增和修改，新增、修改请忽略此字段，如需修改使用素金的金价修改接口
                            if (hsParam.ContainsKey("GoldPrice"))
                                hsParam.Remove("GoldPrice");
                            strParam = JsonConvert.SerializeObject(hsParam); 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionPrimeGoldsOprateUrl, primeGolds.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
                else if (goodsType == GoodsType.InlaySettings)
                {
                    InlaySettings inlaySettings = Json.Deserialize<InlaySettings>(strParam);
                    filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, GoodsType.InlaySettings);
                    var productIdsStr = GetIdsStrParamByIds(new int[] { inlaySettings.ID }); //加入 useDict：true等元素 
                    string responseJson = AllProduct(tttagKey, productIdsStr, filterUrl);
                    Products<InlaySettings> list = JsonConvert.DeserializeObject<Products<InlaySettings>>(responseJson);
                    if (list.Rows.Count == 1)
                    {
                        if (list.Rows[0].ReceiptStatus == inlaySettings.ReceiptStatus)
                        { 
                            //更新
                            return AllProduct(tttagKey, strParam, string.Format(GlobalConfig.TransmissionInlaySettingsOprateUrl, inlaySettings.ID), "put");
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("不能修改付款状态");
                        }
                    }
                }
            }
            else
            {
                return CommonLog.MsgErrorInfo("未指定商品类别");
            }
            return "";
        }
        /// <summary>
        /// 付款操作
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string UpdateProductPayStatus(string strParam)
        { 
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam,"付款"); 
            try
            {
                #region 获取产品类别
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定商品类别");
                }
                int goodsType = hsParam.GetInt("GoodsType").Value;
                string productName = GoodsType.GetTypeName(goodsType);
                hsParam.Remove("GoodsType");
                strParam = JsonConvert.SerializeObject(hsParam);
                string filterUrl = GoodsType.GetGoodsUrlByTypId(GlobalConfig.TransmissionBatch, goodsType);
                #endregion
                using (ITransaction trans_payOrders = YZ.GetTransaction(tttagKey))
                {
                    #region 增加付款账户 流水记录
                    decimal? totalRMB = 0, totalUSD = 0;
                    BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", hsParam.GetInt("BankID"));
                    if (_bank != null)
                    {
                        //Currency=1   是RMB  2是美金 
                        if (hsParam.GetInt("Currency") == 1 && hsParam.GetInt("Currency") == _bank.Currency)
                        {
                            if (_bank.BankBalance >= Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney"))) && _bank.BankBalance > 0)
                            {
                                _bank.BankBalance = _bank.BankBalance + (-Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney"))));//加减数 
                                totalRMB += Math.Round(Convert.ToDecimal(hsParam.GetString("TotalMoney")));
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("【全部付】￥账户余额不足");
                            }
                        }
                        else if (hsParam.GetInt("Currency") == 2 && hsParam.GetInt("Currency") == _bank.Currency)
                        {
                            if (_bank.BankBalance >= Convert.ToDecimal(hsParam.GetString("TotalMoney")) && _bank.BankBalance > 0)
                            {
                                _bank.BankBalance = _bank.BankBalance + (-Convert.ToDecimal(hsParam.GetString("TotalMoney")));//加减数 
                                totalUSD += Convert.ToDecimal(hsParam.GetString("TotalMoney"));
                            }
                            else
                            {
                                return CommonLog.MsgErrorInfo("【全部付】$账户余额不足");
                            }
                        }
                        else
                        {
                            return CommonLog.MsgErrorInfo("请选择对应币种的账户");
                        }
                        //更新账户余额
                        #region
                        int editBalanceResult = trans_payOrders.Edit(_bank);//更新客户余额事务 要用Edit 
                        if (editBalanceResult > 0)
                        {
                        }
                        else
                        {
                            //跳出
                            return CommonLog.MsgErrorInfo("账户不存在");
                        }
                        #endregion
                        //生成流水
                        #region
                        FlowInfo _flow = new FlowInfo();
                        _flow.CreateTime = DateTime.Now;
                        _flow.UpdateTime = DateTime.Now;
                        if (_bank.Currency == 1)
                        {
                            _flow.Amount = totalRMB;
                        }
                        else if (_bank.Currency == 2)
                        {
                            _flow.Amount = totalUSD;
                        }
                        _flow.Balance = _bank.BankBalance;
                        _flow.Currency = _bank.Currency;
                        _flow.Account = _bank.BankID;
                        _flow.Type = 2;
                        _flow.Abstract = 0;//0订单付款
                        _flow.Purpose = 1;//1裸钻 
                        _flow.ApplyID = hsParam.GetInt("UserID");
                        _flow.ReviewID = hsParam.GetInt("UserID");
                        _flow.ArrivalTime = hsParam.GetDataTime("ArrivalTime");
                        _flow.Status = 1;
                        _flow.Remarks = productName + "现货付款";
                        int addFlowResult = trans_payOrders.Add(_flow);
                        if (addFlowResult > 0)
                        {
                            //继续
                            hsParam.Remove("BankID");
                            hsParam.Remove("ArrivalTime");
                            hsParam.Remove("TotalMoney");
                            hsParam.Remove("UserID");
                            hsParam.Remove("Currency");
                            strParam = JsonConvert.SerializeObject(hsParam);
                            #region 更新数据中心付款状态
                            TransmissionOrderResult tor = new TransmissionOrderResult();
                            int totalSeconds;
                            string signStr;
                            var guid = Guid.NewGuid().ToString();
                            var objParams = JsonConvert.DeserializeObject<JObject>(strParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法
                            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                            MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);
                            //获取数据仓库库存（远程） 多个ID获取多条库存
                            var result =
                                 MyHttpRequest.PostJSONByRequestParam(
                                    new RequestInfo() { RequestJson = strParam, RequestUrl = filterUrl }
                                     , 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.PUT
                            );
                            if (result.Contains(".py"))
                            {
                                trans_payOrders.RollBackTransaction();// 
                                result = CommonLog.MsgErrorInfo("数据远程服务错误");
                            }
                            if (result.Split(':')[1].Replace("}", "").Trim() == "true")
                            {
                                result = CommonLog.MsgSuccessInfo("修改成功");
                                trans_payOrders.CommitTransaction();//更新成功 
                            }
                            else
                            {
                                trans_payOrders.RollBackTransaction();
                                result = CommonLog.MsgErrorInfo(result);
                            }
                            return result;
                            #endregion
                        }
                        else
                        {
                            //跳出
                            trans_payOrders.RollBackTransaction();//更新成功
                            return CommonLog.MsgErrorInfo("生成流水失败");
                        }
                        #endregion
                    }
                    else
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("账户不存在,检查账户标识");
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #endregion
        #region 客户相关

        /// <summary>
        /// 所有客户 9-6
        /// </summary>
        /// <param name="getCustomersParam"></param>
        /// <returns></returns>
        public static string GetCustomerList(string strParam)
        {
            var logParam = strParam;
            HashParam param = Json.Deserialize<HashParam>(strParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, strParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                IList<CustomerInfo> _customersInfo = YZ.GetDatabase(tttagKey).QueryForList<CustomerInfo>("Customer.GetList", param);//ToInt32 9-6
                if (_customersInfo != null && _customersInfo.Count > 0)
                {
                    return CommonLog.MsgSuccessObj( JsonConvert.SerializeObject(_customersInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #endregion

        #region Notice通知相关
        /// <summary>
        /// 单个公告
        /// </summary>
        /// <param name="customerInfoParam"></param>
        /// <returns></returns>
        public static string GetNoticeInfo(string noticeInfoParam)
        {
            var logParam = noticeInfoParam;
            string tttagKey = CommonUrl.getURL(null, noticeInfoParam);
            //templateJSON
            NoticeInfo param = Json.Deserialize<NoticeInfo>(noticeInfoParam); //解析Android传过来的Json   //Deserialize 反序列化
            try
            {
                NoticeInfo notice = YZ.GetDatabase(tttagKey).Get<NoticeInfo>(param);
                if (notice != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(notice));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取失败,请检查标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 浏览公告
        /// </summary>
        /// <param name="noticeInfoParam"></param>
        /// <returns></returns>
        public static string ViewNoticeInfo(string viewNoticeInfoParam)
        {
            var logParam = viewNoticeInfoParam;
            string tttagKey = CommonUrl.getURL(null, viewNoticeInfoParam);
            //templateJSON
            NoticeInfo param = Json.Deserialize<NoticeInfo>(viewNoticeInfoParam);
            try
            {
                NoticeInfo notice = YZ.GetDatabase(tttagKey).Get<NoticeInfo>(param);
                if (notice != null)
                {
                    notice.PageView++;
                    int editResult = YZ.GetDatabase(tttagKey).Edit(notice);
                    if (editResult > 0)
                    {
                        return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(notice));
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("更新失败,公告不存在");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("公告不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 发布公告
        /// </summary>
        /// <param name="addCustomerParam"></param>
        /// <returns></returns>
        public static string AddNotice(string addNoticeParam)
        {
            var logParam = addNoticeParam;
            string tttagKey = CommonUrl.getURL(null, addNoticeParam);
            //UserPassword(必传)
            //templateJSON
            NoticeInfo param = Json.Deserialize<NoticeInfo>(addNoticeParam);
            param.CreateTime = DateTime.Now;//注册时间
            try
            {
                using (ITransaction trans_addNotice = YZ.GetTransaction(tttagKey))
                {
                    int addNoticeResult = trans_addNotice.Add(param);
                    if (addNoticeResult > 0)
                    {
                        try
                        {
                            trans_addNotice.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("添加成功");
                        }
                        catch (Exception e)
                        {
                            trans_addNotice.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("添加失败:");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("添加失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("添加失败，程序错误");
            }
        }
        /// <summary>
        /// 修改公告
        /// </summary>
        /// <param name="editCustomerParam"></param>
        /// <returns></returns>
        public static string EditNotice(string editNoticeParam)
        {
            var logParam = editNoticeParam;
            string tttagKey = CommonUrl.getURL(null, editNoticeParam);
            //CustomerID（必传）
            //templateJSON
            NoticeInfo param = Json.Deserialize<NoticeInfo>(editNoticeParam);
            try
            {
                using (ITransaction trans_editNotice = YZ.GetTransaction(tttagKey))
                {
                    int editNoticeResult = trans_editNotice.Edit(param);
                    if (editNoticeResult > 0)
                    {
                        try
                        {
                            trans_editNotice.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("修改成功");
                        }
                        catch (Exception e)
                        {
                            trans_editNotice.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("修改失败:");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("修改失败，标识不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("修改失败，程序错误");
            }
        }
        /// <summary>
        ///  紧急通知
        /// </summary>
        /// <returns></returns>
        public static string GetNotice(string param)
        {
            try
            {
                var logParam = param;
                string tttagKey = CommonUrl.getURL(null, param);
                HashResult h = YZ.GetDatabase(tttagKey).QueryForObject<HashResult>("Notice.GetUpdateNotice", null);
                return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(h));
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 所有公告
        /// </summary>
        /// <param name="getCustomersParam"></param>
        /// <returns></returns>
        public static string GetNotices(string getNoticesParam)
        {
            var logParam = getNoticesParam;
            HashParam param = Json.Deserialize<HashParam>(getNoticesParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getNoticesParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                PageList<NoticeInfo> _noticesInfo = YZ.GetDatabase(tttagKey).QueryForList<NoticeInfo>("Notice.GetList", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));//ToInt32 9-6
                if (_noticesInfo != null && _noticesInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_noticesInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载公告失败，程序错误");
            }
        }
        /// <summary>
        /// 所有发布中公告 11-16
        /// </summary>
        /// <param name="getNoticesParam"></param>
        /// <returns></returns>
        public static string GetNoticeList(string getNoticeListParam)
        {
            var logParam = getNoticeListParam;
            HashParam param = Json.Deserialize<HashParam>(getNoticeListParam);//PageParam是个坑 9-6
            string tttagKey = CommonUrl.getURL(param, getNoticeListParam);
            //参数可全空
            //#msg 和"#msg"
            try
            {
                PageList<NoticeInfo> _noticesInfo = YZ.GetDatabase(tttagKey).QueryForList<NoticeInfo>("Notice.NoticeList", param, Convert.ToInt32(param.GetInt("PageSize")), Convert.ToInt32(param.GetInt("PageIndex")));//ToInt32 9-6
                if (_noticesInfo != null && _noticesInfo.Data.Count > 0)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(_noticesInfo));
                }
                else
                {
                    //空
                    return CommonLog.MsgErrorInfo("没有任何记录");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("加载公告失败，程序错误");
            }
        }
        #endregion

        #region 上传现货 excel csv
        /// <summary>
        /// 上传excel csv
        /// </summary>
        /// <param name="request"></param>
        /// <param name="RequestUrl"></param>
        /// <param name="sbStr"></param>
        /// <returns></returns>
        public static  UpFileResult UpLoadPart2(FileUploadMessage request, string RequestUrl, string sbStr)
        {
            var logParam = string.Format("request.FileName:{0},RequestUrl:{1},sbStr:{2}", request.FileName, RequestUrl, sbStr);
            string tttagKey = request.key; 
            UpFileResult result = new UpFileResult();
            try
            {
                //处理fileName
                string partUrl = "";
                if (request.FileName.LastIndexOf('?') > 0)
                {
                    partUrl = request.FileName.Substring(request.FileName.LastIndexOf('?'));//得到剩下的url
                    request.FileName = request.FileName.Replace(partUrl, "");
                }
                if (sbStr == "" && partUrl != "") //彩宝，统包，成品过来
                { 
                    Dictionary<string, string> dict = MyHttpRequest.GetParams(partUrl);
                    sbStr = MyHttpRequest.ShotDic(dict).ToString();
                }
                int totalSeconds;
                string signStr;
                //签名
                string guid = Guid.NewGuid().ToString();
                MyHttpRequest.SignByParams(guid, sbStr, request.key, out totalSeconds, out signStr);
                //发送带签名的参数
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");//保持长连接
                using (var content = new MultipartFormDataContent())
                {
                    var fileContent = new StreamContent(request.FileData);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = request.FileName, Name = "file_data" };
                    content.Add(fileContent);
                    content.Headers.Add("UUID", guid);
                    content.Headers.Add("Auth", signStr);
                    content.Headers.Add("Time", totalSeconds.ToString());
                    //提交数据中心
                    var responseJson = httpClient.PostAsync(RequestUrl + partUrl, content)
                     .Result.Content.ReadAsStringAsync().Result;
                    result.Message = @responseJson;//上传结果
                    result.IsSuccess = @responseJson.Contains("result\":\"true");
                }
                return result;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                throw;
            }
        }
        /// <summary>
        #endregion
        #region 供应商
        /// <summary>
        /// 获取供应商的倍率
        /// </summary>
        /// <param name="Supplier"></param>
        /// <param name="goodsType"></param>
        /// <returns></returns>
        public static decimal GetSuppplierRate(string tttagKey, string Supplier, int goodsType)
        {
            decimal rate = 1;
            SupplierInfo supplier = Yunzuan.Common.DiamondsPriceHandlers.GetSuppliers(tttagKey, Supplier);
            if (goodsType == GoodsType.Diamond)
            {
                rate = supplier.Rebate.Value;
            }
            else if (goodsType == GoodsType.Parcel)
            {
                rate = supplier.ParcelRebate.Value;
            }
            else if (goodsType == GoodsType.Ring)
            {
                rate = supplier.RingRebate.Value;
            }
            else if (goodsType == GoodsType.Gem)
            {
                rate = supplier.GemRebate.Value;
            }
            else if (goodsType == GoodsType.Emerald)
            {
                rate = supplier.EmeraldRebate.Value;
            }
            else if (goodsType == GoodsType.PrimeGolds)
            {
                rate = supplier.PrimeGoldRebate.Value;
            }
            else if (goodsType == GoodsType.InlaySettings)
            {
                rate = supplier.InlaySettingsRebate.Value;
            }
            return rate;
        }
        #endregion
        #region 
        public static decimal GetGroupAmountByProduct(int lib, string str, decimal current_price, string key)
        {
            //解析规则字符串
            if (str == null || str == "" || str.Trim().Length < 1) return 1;
            else
            {
                IList<Group_Amount> lv2Amounts = new List<Group_Amount>();
                if (System.Web.HttpContext.Current.Cache.Get("Cache:GroupAmout" + key + lib.ToString()) == null)
                {
                    if (str.LastIndexOf(";") == str.Length - 1)  //去多组合的末尾;
                        str = str.Substring(0, str.Length - 1);
                    string[] obj = str.Replace("\n", "").Replace("\r", "").Split(';');  //分组存相对应的折扣
                    //1.形状
                    for (int i = 0; i < obj.Length; i++)
                    {
                        Group_Amount lv2Amount = new Group_Amount();
                        //9999.99-#0.99#;10000-19999.99#0.89#;50000+#1.11#;
                        string[] temps = obj[i].Split('#');
                        if (temps.Length > 1)
                        {
                            //2.重量
                            if (temps[0].Contains("-"))
                            {
                                var prices = temps[0].Split('-');
                                if (prices[1] == "")//指1w以下 9999.99-
                                {
                                    lv2Amount.MaxAmount = Convert.ToDecimal(prices[0]);
                                    lv2Amount.MinAmount = Convert.ToDecimal(0);
                                }
                                else
                                {
                                    lv2Amount.MaxAmount = Convert.ToDecimal(prices[1]);
                                    lv2Amount.MinAmount = Convert.ToDecimal(prices[0]);
                                }
                            }
                            else if (temps[0].Contains("+"))//处理规则中的特殊替代字符
                            {
                                lv2Amount.MinAmount = Convert.ToDecimal(temps[0].Replace("+", ""));//处理规则中的特殊替代字符
                                lv2Amount.MaxAmount = 999999999.99M;
                            }
                            else
                            {
                                lv2Amount.MaxAmount = 999999999.99M;
                                lv2Amount.MinAmount = 0;
                            }
                            lv2Amount.Double = temps[1] == "" ? 1 : Convert.ToDecimal(temps[1]);
                            lv2Amount.Dis = temps[2] == "" ? 0 : Convert.ToDecimal(temps[2]);
                            lv2Amounts.Add(lv2Amount);
                        }
                    }
                    //第一次访问5分钟后过期，免得修改了4c或金额得改缓存设置
                    System.Web.HttpContext.Current.Cache.Insert("Cache:GroupAmout" + key + lib.ToString(), lv2Amounts, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
                }
                else
                {
                    lv2Amounts = System.Web.HttpContext.Current.Cache.Get("Cache:GroupAmout" + key + lib.ToString()) as IList<Group_Amount>;
                }
                //开始计算
                foreach (var item in lv2Amounts)
                {
                    if (current_price >= item.MinAmount && current_price <= item.MaxAmount)
                    {
                        if (item.Dis != 0) //计算折扣
                            current_price = current_price * ((100 - item.Dis) / 100);
                        else //计算倍率
                        {
                            // current_price = current_price * item.Double; 之前的算法
                            return item.Double;

                        }
                        break;
                    }
                }
                return 1;
            }
        }
        #endregion

        #region 非裸钻计算价格
        public static void CalcPrice<T>(dynamic item, string tttagKey, int goodsType, SysSettingInfo settingInfo, decimal customerRate ,CustomerInfo customer, string SecondSN = "")
        { 
            //供应商的倍率
            decimal supplierRate = 1;
            //全局商品的倍率
            decimal settingRate = 1;
            if (item.Supplier == SecondSN && SecondSN != "")
                supplierRate = 1;
            else
                supplierRate = CRetails.GetSuppplierRate(tttagKey, item.Supplier, goodsType);

            if (goodsType == GoodsType.InlaySettings)
            {
                decimal CustomerRMB = (item.GoldPrice * item.NetGoldWeight * (1 + item.Wastage)) + item.SideLaborFee * item.SideNum + item.SidePrice + item.LaborFee + item.Insurance;
                if (customer != null)
                {
                    if (customer.IsSetInlaySettings == 0)
                    {
                        if (item.Supplier == SecondSN && SecondSN != "")
                            customerRate = 1;
                        else
                            customerRate = (customer.InlaySettingsRebate == "" ? 1 : Convert.ToDecimal(customer.InlaySettingsRebate));
                        //客户的折扣 *全局商品的倍率 * 供应商的倍率 
                        item.Price = CustomerRMB * (1 + (supplierRate - 1) + (settingRate - 1) + (customerRate - 1));
                        //反推出最后的结果
                        item.CustomerGoldPrice = Math.Round(item.GoldPrice * customerRate);//金价
                        item.CustomerWastage = item.Wastage;//损耗
                        item.CustomerSideLaborFee = Math.Round(item.SideLaborFee * customerRate);//副石工费
                        item.CustomerLaborFee = Math.Round(item.LaborFee * customerRate);//工费
                        item.CustomerSidePrice = Math.Round(item.SidePrice * customerRate);//副石总额
                        item.CustomerInsurance = Math.Round(item.Insurance * customerRate); //保险费 
                    }
                    else if (customer.IsSetInlaySettings == 1)
                    {
                        CustomerSetInlaySetttings setInlaySetttings = Json.Deserialize<CustomerSetInlaySetttings>(customer.InlaySettingsRebate);
                        if (item.Supplier == SecondSN && SecondSN != "")
                        {
                            setInlaySetttings.GoldPrice = 0;
                            setInlaySetttings.SideLaborFee = 0;
                            setInlaySetttings.Wastage = 0;
                            setInlaySetttings.LaborFee = 1;
                            setInlaySetttings.SidePrice = 1;
                            setInlaySetttings.Insurance = 1;
                        }
                        //在原价的基础上 对客户设置空托的加价系数 得到的结果
                        decimal CustomerRMB1 = ((item.GoldPrice + setInlaySetttings.GoldPrice) * item.NetGoldWeight * (1 + item.Wastage + setInlaySetttings.Wastage / 100)) //金价*净金重*（1+损耗）
                                            + (item.SideLaborFee + setInlaySetttings.SideLaborFee) * item.SideNum//   副石工费 * 副石粒数
                                            + (item.LaborFee * setInlaySetttings.LaborFee) //工费
                                            + (item.SidePrice * setInlaySetttings.SidePrice) //副石总额
                                            + (item.Insurance * setInlaySetttings.Insurance);//保险费
                                                                                             //CustomerRMB1 /原卖价 得到一个相应的倍率  
                        decimal resultDisc = (1 + (supplierRate - 1) + (settingRate - 1) + ((CustomerRMB1 / CustomerRMB) - 1));
                        if (resultDisc == CustomerRMB1 / CustomerRMB)
                        {
                            //这是客户购买空托的时候 金价 损耗  副石工费  工费  副石总额  保险费
                            item.CustomerGoldPrice = item.GoldPrice + setInlaySetttings.GoldPrice;//金价
                            item.CustomerWastage = item.Wastage + setInlaySetttings.Wastage / 100;//损耗
                            item.CustomerSideLaborFee = item.SideLaborFee + setInlaySetttings.SideLaborFee;//副石工费
                            item.CustomerLaborFee = item.LaborFee * setInlaySetttings.LaborFee;//工费
                            item.CustomerSidePrice = item.SidePrice * setInlaySetttings.SidePrice;//副石总额
                            item.CustomerInsurance = item.Insurance * setInlaySetttings.Insurance; //保险费
                        }
                        else
                        {
                            //反推出最后的结果
                            item.CustomerGoldPrice = Math.Round(item.GoldPrice * resultDisc);//金价
                            item.CustomerWastage = item.Wastage;//损耗
                            item.CustomerSideLaborFee = Math.Round(item.SideLaborFee * resultDisc);//副石工费
                            item.CustomerLaborFee = Math.Round(item.LaborFee * resultDisc);//工费
                            item.CustomerSidePrice = Math.Round(item.SidePrice * resultDisc);//副石总额
                            item.CustomerInsurance = Math.Round(item.Insurance * resultDisc); //保险费 
                        }
                        item.Price = CustomerRMB * resultDisc;
                    }
                }
                else
                {
                    item.Price = CustomerRMB * supplierRate * settingRate;
                }

            }
            else if (goodsType == GoodsType.PrimeGolds)
            {
                if (item.Supplier == SecondSN && SecondSN != "")
                    settingRate = 1;
                else
                    settingRate = CRetails.GetGroupAmountByProduct(goodsType, settingInfo.GroupAmount, item.Price, tttagKey);
                item.Price = item.TotalWeight * (item.GoldPrice + item.LaborFee) * supplierRate * settingRate * customerRate;
            }
            else
            {
                if (item.Supplier== SecondSN &&  SecondSN != "")
                    settingRate = 1;
                else
                    settingRate = CRetails.GetGroupAmountByProduct(goodsType, settingInfo.GroupAmount, item.Price, tttagKey);
                //客户的折扣 *全局商品的倍率 * 供应商的倍率
                item.Price = item.Price * settingRate * supplierRate * customerRate;
            }
        }
        #endregion

        #region  
        #endregion
    }
}
